package com.aoxun.core.util;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 百度语音合成
 * @author zhang_xf
 * @date  2017-5-26上午11:17:32
 */
public class TextToAudioUtils {
	
    //百度应用 APPID
    public static final String APP_ID = "10704292"; 
    //百度应用APIKEY
    public static final String API_KEY = "h5mFWe57v9AZuk45seAyZHuC";
    //百度应用SECRET_KEY
    public static final String SECRET_KEY = "366d13d4793adf3abc13e7cd68c198a5";
    //百度API 文字合成语音URL
	public static final String TEXT2AUDIO_URL = "https://tsn.baidu.com/text2audio";
	//百度API 获取语音合成access_token
	public static final String ACCESSTOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
	public static void main(String[] args) throws Exception {
		String tex = "欢迎【姓名】同志暨临公司考察指导";
		TextToAudioUtils audio = new TextToAudioUtils();
		String accessToken=audio.getAccessToken();

		System.out.println(accessToken);
		audio.text2Audio(tex,accessToken,"1",getRandomStringByLength(60),"","","6","1");
	}
	/**
	 * 所有参数方法
	 * @Title text2Audio
	 * @param tex	必填	合成的文本，使用UTF-8编码，请注意文本长度必须小于1024字节
	 * @param lan	必填	语言选择,填写zh
	 * @param tok	必填	开放平台获取到的开发者access_token
	 * @param ctp	必填	客户端类型选择，web端填写1
	 * @param cuid	必填	用户唯一标识，用来区分用户，填写机器 MAC 地址或 IMEI 码，长度为60以内
	 * @param spd	选填	语速，取值0-9，默认为5中语速
	 * @param pit	选填	音调，取值0-9，默认为5中语调
	 * @param vol	选填	音量，取值0-9，默认为5中音量
	 * @param per	选填	发音人选择, 0为女声，1为男声，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
	 * @author zhang_xf丶
	 * @throws Exception 
	 * @date 2017-5-26
	 */
	@SuppressWarnings("static-access")
	public void text2Audio(String tex,String tok,String ctp,String cuid,String spd,String pit,String vol,String per) throws Exception{
		String params = "tex=" + URLEncoder.encode(tex, "UTF-8")
				+ "&lan=zh&cuid=" + cuid + "&ctp=1&tok=" + tok + "&spd=" + spd
				+ "&pit=" + pit + "&vol=" + vol + "&per=" + per;
		System.out.println(params);
		String data = this.postVoice(TEXT2AUDIO_URL,params);
		System.out.println("文件保存路径:"+data);
	}
	/**
	 * 必填参数方法
	 * @Title text2Audio
	 * @param tex	必填	合成的文本，使用UTF-8编码，请注意文本长度必须小于1024字节
	 * @param lan	必填	语言选择,填写zh
	 * @param tok	必填	开放平台获取到的开发者access_token
	 * @param ctp	必填	客户端类型选择，web端填写1
	 * @param cuid	必填	用户唯一标识，用来区分用户，填写机器 MAC 地址或 IMEI 码，长度为60以内
	 * @author zhang_xf丶
	 * @throws Exception 
	 * @date 2017-5-26
	 */
	@SuppressWarnings("static-access")
	public static void text2Audio(String tex,String tok,String ctp,String cuid) throws Exception{
		
		//不传此参数  客户端类型默认为 web端
		if(StringUtils.isEmpty(ctp)) {
			ctp="1";
		}
		
		String params = "tex=" + URLEncoder.encode(tex, "UTF-8")
				+ "&lan=zh&cuid=" + cuid + "&ctp=1&tok=" + tok;
		System.out.println(params);
		String data = postVoice(TEXT2AUDIO_URL,params);
		System.out.println("文件保存路径:"+data);
	}
	
	/**
     * 语音合成HTTP方法
     * @param requestUrl 请求的接口地址 拼接access_token后的
     * @param params 语音合成的参数
     * @throws Exception
     */
    public static String postVoice(String requestUrl,String params) throws Exception {
    	String workspace = "E:/";
    	String path = workspace+"/text2audio/";
    	try {
			if (!(new File(path).isDirectory())) {
				new File(path).mkdir();
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
    	String filePath = path+"VOICE"+new Date().getTime()/1000+".mp3";
        String generalUrl = requestUrl;
        URL url = new URL(generalUrl);
        System.out.println(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    	System.out.println("打开链接，开始发送请求"+new Date().getTime()/1000);
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(params);
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
        		System.out.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        InputStream inputStream = connection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len=inputStream.read(buffer))!=-1) {
        	outputStream.write(buffer,0,len);
		}
        outputStream.close();
        System.out.println("请求结束"+new Date().getTime()/1000);
        System.out.println("MP3文件保存目录:" + filePath);
        return filePath;
    }
    
    /**
     * 获取一定长度的随机字符串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    
   /**
    * 获取Access Token
    * @return 
    * @throws Exception
    */
    public static String getAccessToken() throws Exception {
    	 String result =""; 
    	 String accessToken="";
         BufferedReader in = null;
         try {
             String urlNameString =ACCESSTOKEN_URL+"?grant_type=client_credentials&"
         	 		+ "client_id="+API_KEY+"&"
        	 		+ "client_secret="+SECRET_KEY;
             URL realUrl = new URL(urlNameString);
             // 打开和URL之间的连接
             URLConnection connection = realUrl.openConnection();
             // 设置通用的请求属性
             connection.setRequestProperty("accept", "*/*");
             connection.setRequestProperty("connection", "Keep-Alive");
             // 建立实际的连接
             connection.connect();
             // 获取所有响应头字段
             Map<String, List<String>> map = connection.getHeaderFields();
             // 遍历所有的响应头字段
             for (String key : map.keySet()) {
                 System.out.println(key + "--->" + map.get(key));
             }
             // 定义 BufferedReader输入流来读取URL的响应
             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
             String line;
             while ((line = in.readLine()) != null) {
                 result += line;
             }
             
             if(StringUtils.isNotEmpty(result)) {
            	 JSONObject json=JSONObject.parseObject(result);
            	 accessToken=json.getString("access_token");
             }
             
         } catch (Exception e) {
             System.out.println("发送GET请求出现异常！" + e);
             e.printStackTrace();
         }
         // 使用finally块来关闭输入流
         finally {
             try {
                 if (in != null) {
                     in.close();
                 }
             } catch (Exception e2) {
                 e2.printStackTrace();
             }
         }
         return accessToken;
    }
}